<?php
/**
 * 前台control父类,店铺control父类,会员control父类
 *
 *
 * @copyright  Copyright (c) 2015-2016 bearshop Inc. (http://www.smallbearshop.net)
 * @license    http://www.smallbearshop.net
 * @link       http://www.smallbearshop.net
 * @since      File available since Release v1.1
 */
defined('Inbearshop') or exit('Access Invalid!');
class Control{
	public function __construct(){
		//检测网站是否关闭
		if($GLOBALS['setting_config']['site_status'] != 1){
			echo $GLOBALS['setting_config']['closed_reason'];
			exit;
		}
		
		$wxaccount = F('wxaccount');
		Tpl::output('site_name',$wxaccount['wx_name']);
		
	}
	protected $layout	=	null;
	protected function showTip($msg,$url='',$show_type='html',$msg_type='succ',$is_show=1,$time=2000){
		/**
		 * 如果默认为空，则跳转至上一步链接
		 */
		$url = ($url!='' ? $url : getReferer());
		$msg_type = in_array($msg_type,array('succ','error')) ? $msg_type : 'error';
		if (is_array($url)){
			foreach ($url as $k => $v){
				$url[$k]['url'] = $v['url']?$v['url']:getReferer();
			}
		}
		/**
		 * 读取信息布局的语言包
		 */
		Language::read("msg");
		Language::read('common');
		/**
		 * html输出形式
		 * 指定为指定项目目录下的error模板文件
		 */
		Tpl::setDir('');
		Tpl::output('html_title',Language::get('bearshop_html_title'));
		Tpl::output('msg',$msg);
		Tpl::output('url',$url);
		Tpl::output('msg_type',$msg_type);
		Tpl::output('is_show',$is_show);
		Tpl::showpage('msg',$this->layout,$time);
		exit;
	}
	
	/*
	 * 从新获取access_token
	*/
	public function getAccessTokenApi(){
	
		$model = Model();
		$wx_info = $model->table('wxaccount')->where(array('wx_id'=>'1'))->find();
		$appid = $wx_info['wx_appid'];
		$appsecret = $wx_info['wx_appsecret'];
		$accesstime = $wx_info['wx_access_time'];
		
		if(($accesstime+3600)<time()){
			$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
			$output = $this->https_request($url);
			$jsoninfo = json_decode($output, true);
			$access_token = $jsoninfo["access_token"];
			$model = Model();
			$params = array();
			$params['wx_accesstoken'] = $access_token;
			$params['wx_access_time'] = time();
			$model->table('wxaccount')->where(array('wx_id'=>1))->update($params);
			return $access_token;
		}else{
			return $wx_info['wx_accesstoken'];
		}
	}
	
	/*
	 * 获取accesstoken
	 * 小熊Shop
	 */
	public function getAccessTokenIn(){
		$model = Model();
		$wx_info = $model->table('wxaccount')->where(array('wx_id'=>1))->find();
		return $wx_info['wx_accesstoken'];
	}
	
	public function getAccessToken(){
		
		$model = Model();
		$wx_info = $model->table('wxaccount')->where(array('wx_id'=>'1'))->find();
		$appid = $wx_info['wx_appid'];
		$appsecret = $wx_info['wx_appsecret'];
		$accesstime = $wx_info['wx_access_time'];
		
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
		$output = $this->https_request($url);
		$jsoninfo = json_decode($output, true);
		$access_token = $jsoninfo["access_token"];
		$model = Model();
		$params = array();
		$params['wx_accesstoken'] = $access_token;
		$params['wx_access_time'] = time();
		$model->table('wxaccount')->where(array('wx_id'=>1))->update($params);
		return $access_token;
	}
	
	public function tuiinfo($auction_id,$end_time){		

		$model = Model();
		$auction = $model->table('auction')->where(array('id'=>$auction_id))->find();

		$user = $model->table('user')->where(array('user_id'=>$auction['seller_id']))->find();
		$date = date("m月d日 H:i",$end_time);

		$url = BASE_SITE_URL.'/index.php?act=index&auction_id='.$auction['id'];
		$content = "朋友圈分享文字，提供参考：\n{$auction['auction_description']}\n";
		$content.= "截拍时间：".$date."\n点击链接出价\n";
		
		//$url = "<a href='".$url."'>{$url}</a>";

		$content = $content.$url;		
		$txt = '{
					"touser":"'.$user['openid'].'",
					"msgtype":"text",
					"text":{
						"content":"'.$content.'"
					}
				}';
	
		$access_token = $this->getAccessTokenIn();		
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
		$data = $this->https_request($url,$txt);
		$data = json_decode($data,true);
		if($data['errmsg']!='ok'){
			$access_token = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
			$data = $this->https_request($url,$txt);
		}
		
		return true;
	}
	
	public function send_template_message($data){
		$access_token = $this->getAccessTokenIn();
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
		$res = $this->https_request($url,$data);
		$data = json_decode($res,true);
		
		if($data['errmsg']!='ok'){
			$access_token = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
			$res = $this->https_request($url,$data);
			$data = json_decode($res,true);
		}
		
		return $data;
	}
	
	/*
	 * $url 接口API
	 * $data json数据
	 */
	protected function https_request($url,$data = null)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	
	/*
	 * 订单号
	*/
	public function snOrder() {
		$this->order_sn = date('Ymd').substr( implode(NULL,array_map('ord',str_split(substr(uniqid(),7,13),1))) , -8 , 8);
		$model = Model();
		$info = $model->table('order')->where(array('order_sn'=>$this->order_sn))->find();
		if(!empty($info)){
			$this->snOrder();
		}
		return $this->order_sn;
	}
	
	public function addsellerlog($auction_id,$message,$uid){
		
		$params = array();
		$params['auction_id'] = $auction_id;
		$params['uid'] = $uid;
		$params['message'] = $message;
		$params['add_time']= time();
		
		$model = Model();
		$res = $model->table('seller_log')->insert($params,true);
		return $res;
	}
	
	
	public function getTemplateId($id){
		$model = Model();
		$template = $model->table('template')->where(array('id'=>$id))->find();
		
		return $template['template_id'];
	}
	
	public function getUserInfo($openid){
	
		$access_token = $this->getAccessTokenIn();
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
	
		$d = $this->https_request($url);
		$d = json_decode($d,true);
		
		if(!empty($d['errcode'])){
			$access_token = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
			
			$d = $this->https_request($url);
			$d = json_decode($d,true);
		}
		
		$data = array();
		if($d['subscribe']==1){
			$data['subscribe'] = 1;
			$data['subscribe_time'] = $d['subscribe_time'];
			$data['city'] = $d['city'];
			$data['province'] = $d['province'];
			$data['country'] = $d['country'];
		}else{
			$data['subscribe'] = 0;
		}
	
		return $data;
	}
}

class BaseHomeControl extends Control{
	protected $pagesize = '3';

	/**
	 * 构造函数
	 */
	public function __construct(){
		parent::__construct();
		$model = Model();
		//$_COOKIE['user_id'] = 1;
		$user_id = $_COOKIE['user_id'];	
		$pingbi_user = $model->table('user')->where(array('user_id'=>$user_id,'platform_pingbi'=>1))->find();
		if(!empty($pingbi_user)){
			exit;
		}
		$bearshopsetting = F('bearshopsetting');
		if(empty($user_id)){
			$refurl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
			$refurl = str_replace('&','|',$refurl);
			
			$wxaccount = $model->table('wxaccount')->where(array('wx_id'=>1))->find();
			$return_url = BASE_SITE_URL."/index.php?act=oauth&op=getcode&refurl={$refurl}";
			$return_url = urlencode($return_url);
			$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$wxaccount['wx_appid'];
			$url.="&redirect_uri=".$return_url."&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect";
			
			header("Location:$url");
			exit;
		}else{//自动关注
			$guanzhu = $bearshopsetting['auto_guanzhu'];
			if($guanzhu == 1){
				$set_user_id = $model->table('user')->where(array('auto_guanzhu'=>1))->select();

				if(!empty($set_user_id)){
					$user = $model->table('user')->where(array('user_id'=>$user_id))->find();
					foreach($set_user_id as $g){
						$friend_array = array();
						$friend_array['uid'] = $user['user_id'];
						$friend_array['fid'] = $g['user_id'];
						$friend = $model->table('friend')->where($friend_array)->find();
						if(empty($friend)){
							$friend_array['uname'] = $user['nickname'];
							$friend_array['fname'] = $g['nickname'];
							$model->table('friend')->insert($friend_array);
						}
					}
				}
			}
		}
		
		/**
		 * 读取通用、布局的语言包
		 */
		Language::read('home');

		
		/**
		 * 设置模板文件夹路径
		 */
		Tpl::setDir('home');
		
		/**
		 * 设置布局文件内容
		 */
		Tpl::setLayout('home_layout');
		
		/**
		 * 转码
		 */
		if ($_GET['column'] && strtoupper(CHARSET) == 'GBK'){
			$_GET = Language::getGBK($_GET);
		}
		
		$wxaccount = $model->table('wxaccount')->where(array('wx_id'=>'1'))->find();
		require_once BASE_ROOT_PATH.'/shop/control/weixin/jssdk.php';
		$jssdk = new JSSDK($wxaccount['wx_appid'], $wxaccount['wx_appsecret']);
		$signPackage = $jssdk->GetSignPackage();
		
		Tpl::output('signPackage',$signPackage);	
		Tpl::output('appid',$wxaccount['wx_appid']);
		

		if($bearshopsetting['sales_mobile']==1){
			$u = $model->table('user')->where(array('user_id'=>$_COOKIE['user_id']))->find();
			Tpl::output('isauth',$u['isauth']);			
		}
		Tpl::output('is_btwoc',$bearshopsetting['is_btwoc']);
	}

	/**
	 * 商区列表
	 */
	protected function arealist(){
		$cityinfo = $this->city_info;

		$parent_area_id = $cityinfo['area_id'];
		if(!$area_list = F('area_'.$parent_area_id,null,'cache/city')){
			$area_model  = Model('area');
			$area_list = $area_model->getList(array('parent_area_id'=>$parent_area_id),'','area_sort asc');
			
			if(!empty($area_list)){
				foreach($area_list as $key=>$val){
					$area_list[$key][] = $area_model->getList(array('parent_area_id'=>$val['area_id']),'','area_sort asc');		
				}
			}
			F('area_'.$parent_area_id,$area_list,'cache/city');
		}

		Tpl::output('area_list',$area_list);
	}

	/**
	 * 分类列表
	 */
	protected function classlist(){
		$cityinfo = $this->city_info;
		$parent_area_id = $cityinfo['area_id'];
		if(!$class = F('class_'.$parent_area_id,null,'cache/class')){
			$model_class = Model('store_class');
			$class_list = $model_class->getList(TRUE,NULL,'class_sort asc');
			$class_root = array();
			$class_menu = array();
			
			if(!empty($class_list)){
				foreach($class_list as $key=>$val){
					if($val['parent_class_id'] == 0){
						$class_root[] = $class_list[$key];
					}else{
						$class_menu[$val['parent_class_id']][] = $class_list[$key];
					}
				}
			}
			$class = array('class_root'=>$class_root,'class_menu'=>$class_menu);
			F('class_'.$parent_area_id,$class,'cache/class');
		}
		Tpl::output('class_root',$class['class_root']);
		Tpl::output('class_menu',$class['class_menu']);
	}


	/**
	 * 人均消费
	 */
	protected function pconsume(){
		return	array(
			1	=>	Language::get('offline_20_below'),
			2	=>	Language::get('offline_21_50'),
			3	=>	Language::get('offline_51_80'),
			4	=>	Language::get('offline_81_120'),
			5	=>	Language::get('offline_121_200'),
			6	=>	Language::get('offline_201_500'),
			7	=>	Language::get('offline_500')
		);
	}

	/**
	 * 检测登陆
	 */
	protected function checklogin(){
		if($_COOKIE['is_login']==1){
			@header("Location:index.php");
		}
	}
	
}

